//
//  CatTimingListVController.m
//  DoorBell
//
//  Created by Chun Hung Cheung on 2023/3/18.
//  Copyright © 2023 Chun Hung Cheung. All rights reserved.
//

#import "CatTimingListVController.h"
#import "CatTimingFeedVController.h"
#import "CatTimingListModel.h"
#import "CatTimingListCell.h"
@interface CatTimingListVController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *CatTimingListTableview;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UIButton *addTimeIcon;
@property(nonatomic,strong)NSMutableArray *meta_array;
@property (nonatomic,strong)dispatch_source_t wake_up_timer;
@property(nonatomic, assign)BOOL cancelpost;

@property(nonatomic,strong)UIImageView *no_message_view;
@property(nonatomic,strong)UILabel *no_message_label;
@property(nonatomic,strong)FBDevicesList *list;
@end

@implementation CatTimingListVController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = [UIColor whiteColor];
    [self setup];

}


- (void)meal_plan_result
{
    [SVProgressHUD dismiss];
    
    [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"设置成功",nil)];
     self.cancelpost = NO;
    [YKBusinessFramework equesSendData:[NSString stringWithFormat:@"{\"method\":\"get_control\",\"to\":\"%@\"}",self.bid]];
}


- (void)get_plan
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [YKBusinessFramework equesSendData:[NSString stringWithFormat:@"{\"method\":\"get_control\",\"to\":\"%@\"}",self.bid]];
    });
}


- (void)get_control_result:(NSNotification*)nitification
{
    /*
     {
         code = 0;
         deviceId = 494d396a0929d68420800c3050f3533c;
         method = "get_control";
         setting =     {
             "battery_percentage" = 0;
             "charge_state" = 0;
             "colour_data" = "";
             "cover_state" = on;
             "export_state" = true;
             "factory_reset" = 0;
             "feed_report" = 0;
             "feed_state" = standby;
             "grain_status" = enough;
             "grain_surplus" = 0;
             light = 1;
             "manual_feed" = 2;
             "meal_plan" =         (
                 7f09000101,
                 7f09230101
             );
             "percent_state" = 0;
             play = 0;
             "quick_feed" = 0;
             "slow_feed" = 0;
             switch = 0;
             "unit_switch" = cup;
             "voice_times" = 0;
             "volume_set" = 0;
             weight = 0;
             "weight_calibrate" = 0;
         };
     }
     
      定时计划最多设置10个
     "meal_plan" =         (
         7f09000101,       7f09000101   7f代表周期 转二进制 1111111 1-7为某个位置为1代表设置周几    09带包时间小时 00代表时间分钟  01 代表  开/关
         7f09230101
     );
     
     
     */
    
    
     [SVProgressHUD dismiss];
     NSDictionary *dict = [nitification object];
     NSDictionary *dict2 =  [dict objectForKey:@"setting"];
     NSArray *Array =  [dict2 objectForKey:@"meal_plan"];
     NSString *bid =  [dict objectForKey:@"deviceId"];
     if (![bid isEqualToString:self.bid]) {
        return;
     }
     self.cancelpost = NO;
    if(Array.count > 0){
    
        if (_no_message_view) {
           [_no_message_view removeFromSuperview];
            _no_message_view = nil;
        }
        
        if (_no_message_label) {
           [_no_message_label removeFromSuperview];
            _no_message_label = nil;
        }
        
        [self getdata:Array];
    
    }else{
        [self.dataArray removeAllObjects];
        self.meta_array = [NSMutableArray array];
        self.CatTimingListTableview.backgroundColor = [UIColor whiteColor];
       [self.CatTimingListTableview reloadData];

       
        self.no_message_view.backgroundColor = [UIColor clearColor];
        self.no_message_label.backgroundColor = [UIColor clearColor];
        
        
    }
    
}

- (UIImageView*)no_message_view
{
    if (!_no_message_view) {
         _no_message_view = [[UIImageView alloc]init];
        [self.view addSubview:_no_message_view];
        [_no_message_view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX);
            make.width.mas_equalTo(205);
            make.height.mas_equalTo(140);
            make.top.equalTo(self.view.mas_top).offset(100+[UIDevice dev_navigationFullHeight]);
        }];
        _no_message_view.image = [UIImage imageNamed:@"cat_message_none"];
    }
    return _no_message_view;
}

- (UILabel*)no_message_label
{
    if (!_no_message_label) {
         _no_message_label = [[UILabel alloc]init];
         _no_message_label.userInteractionEnabled = YES;
         _no_message_label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
         _no_message_label.textColor =[HexChangeRGB colorWithHexString:@"#999999"];
         _no_message_label.textAlignment = NSTextAlignmentCenter;
        [_no_message_label sizeToFit];
        [self.view addSubview:_no_message_label];
        [_no_message_label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.no_message_view.mas_bottom).offset(20);
            make.centerX.equalTo(self.view.mas_centerX);
        }];
        _no_message_label.text = NSLocalizedString(@"暂无喂食计划～", nil);
    }
    return _no_message_label;
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if(@available(iOS 15.0,*)){
      UINavigationBarAppearance *apperance=[[UINavigationBarAppearance alloc]init];
      apperance.backgroundColor = [UIColor whiteColor];
      self.navigationController.navigationBar.standardAppearance = apperance;
      self.navigationController.navigationBar.scrollEdgeAppearance = apperance;
    }

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devstClick:) name:@"devst" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(get_control_result:) name:@"get_control" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(meal_plan_result) name:@"meal_plan" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(get_plan) name:@"get_plan" object:nil];
    FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    
    __weak CatTimingListVController *weakSelf = self;
    if (list.status == 2) {
        [SVProgressHUD showWithDuration:15];
        // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
        __block int timeout = 30*200*5; // 倒计时时间
        weakSelf.cancelpost = NO;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        weakSelf.wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(weakSelf.wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
        dispatch_source_set_event_handler(weakSelf.wake_up_timer, ^{
            if(weakSelf.cancelpost){ // 倒计时结束，关闭
                [YKBusinessFramework equesSendData:[NSString stringWithFormat:@"{\"method\":\"get_control\",\"to\":\"%@\"}",self.bid]];
                dispatch_source_cancel(weakSelf.wake_up_timer);
                weakSelf.wake_up_timer = nil;
            }else{
                NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                [YKBusinessFramework equesSendData:Str];
                 timeout-=200;
                if (timeout <= 0) {
                    dispatch_source_cancel(weakSelf.wake_up_timer);
                    weakSelf.wake_up_timer = nil;
                }
            }
        });
         dispatch_resume(_wake_up_timer);
    }else if (list.status == 1){
        [YKBusinessFramework equesSendData:[NSString stringWithFormat:@"{\"method\":\"get_control\",\"to\":\"%@\"}",self.bid]];
    }else {
        
        [SVProgressHUD showWithDuration:10];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [YKBusinessFramework equesSendData:[NSString stringWithFormat:@"{\"method\":\"get_control\",\"to\":\"%@\"}",self.bid]];
        });
        
    }
    
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"devst" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"get_control" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"meal_plan" object:nil];

}

- (void)devstClick:(NSNotification*)notification
{
    /*
     {
         bid = 1fd834a600472ebe24cb01e03f9416d1;
         method = devst;
         name = "e0d31a150c6f-1fd834a6";
         remoteupg = 2;
         role = 27;
         status = 0;
         stat = 0;
         type = 27;
         uid = 1fd834a600472ebe24cb01e03f9416d1;
     }
    */
    
    NSDictionary *dict = (NSDictionary*)notification.object;
    NSString *bid = [dict objectForKey:@"bid"];
    if (![bid isEqualToString:self.bid]) {
         return;
    }

    if ([self.bid isEqualToString:bid] && [[dict objectForKey:@"stat"] intValue] == 1) {
        [SVProgressHUD dismiss];
         self.cancelpost = YES;
    }else{
         self.cancelpost = NO;
    }
}



- (void)getdata:(NSArray*)array
{
    dispatch_async(dispatch_get_main_queue(), ^{
         self.meta_array = [NSMutableArray arrayWithArray:array];
        [self.dataArray removeAllObjects];
         self.dataArray = nil;
         for (int i = 0; i < array.count; i ++) {
             NSString *str = array[i];
            if(str.length == 10){
                [self.dataArray addObject:[self createModel:str]];
            }
         }
        self.CatTimingListTableview.backgroundColor = [UIColor whiteColor];
        
        for (CatTimingListCell *item in self.CatTimingListTableview.visibleCells) {
            if (item.isOpenLeft){
                [item closeLeftSwipe];
            };
        }
        
       [self.CatTimingListTableview reloadData];
  
    });
   
}

- (CatTimingListModel*)createModel:(NSString*)plan
{
    NSString *week = [plan substringWithRange:NSMakeRange(0, 2)];
    
    //16进制转二进制
    NSString *weekstr = [self getBinaryByHex:week];
    
    
    NSString *hourstr = [plan substringWithRange:NSMakeRange(2, 2)];
    
    long long hour = [self convertHexToDecimal:hourstr];
    
    NSString *mintr = [plan substringWithRange:NSMakeRange(4, 2)];
    
    long long min = [self convertHexToDecimal:mintr];
    
    NSString *weighttr = [plan substringWithRange:NSMakeRange(6, 2)];
    
    long long weigh = [self convertHexToDecimal:weighttr];
    
    NSString *timestr = [NSString stringWithFormat:@"%02lld:%02lld",hour,min];

    NSString *status = [plan substringWithRange:NSMakeRange(8, 2)];
    
    
    NSLog(@"转换前周期-- %@   小时-- %@ 分钟-- %@ 份数-- %@ 状态-- %@ \n",week,hourstr,mintr,weighttr,status);
    NSLog(@"转换后周期-- %@ 获得后的周期 -- %@  小时-- %lld 分钟-- %lld timestr -- %@ 份数-- %lld 状态-- %@ \n",[weekstr substringFromIndex:1],[self getWeek:[weekstr substringFromIndex:1]],hour,min,timestr,weigh,status);
    NSString *title;
    title = [NSString stringWithFormat:@"%@ | %lld 份",[self getWeek:[weekstr substringFromIndex:1]],weigh];
    CatTimingListModel *model = [[CatTimingListModel alloc]initWithTime:timestr weak:title foodNumber:weigh status:[status boolValue]];
    model.feedStr = plan;

    return model;
    
}


- (NSMutableArray*)dataArray
{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)setup
{
    self.list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    
     UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
     backbtn.frame = CGRectMake(0,0,40,80);
     backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [backbtn setImage:[UIImage imageNamed:@"cat_alarm_back"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftActionClick) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];
 
    UILabel *titleLabel  = [[UILabel alloc]init];
    titleLabel.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
    titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:20.0];
    titleLabel.text = NSLocalizedString(@"定时",nil);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.frame = CGRectMake(0, 0, 80, 25);
     self.navigationItem.titleView = titleLabel;
    
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.addTimeIcon];
    
}

- (void)selectLeftActionClick
{
    if (_wake_up_timer) {
        dispatch_source_cancel(_wake_up_timer);
        _wake_up_timer = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}




- (UIButton*)addTimeIcon
{
    if (!_addTimeIcon) {
         _addTimeIcon = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        [_addTimeIcon setImage:[UIImage imageNamed:@"cat_timming_add"] forState:UIControlStateNormal];
         _addTimeIcon.userInteractionEnabled = YES;
        [_addTimeIcon addTarget:self action:@selector(tapClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addTimeIcon;
}

- (void)tapClick
{
    

    FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    
    /*
    if ([list.is_share intValue]) {
        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"The invitee does not have permission to change the settings",nil) duration:2];
        return;
    }
    */
    if(list.status == 0){
       [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设备离线无法操作",nil)];
        return;
    }
    
    if (self.meta_array.count >= 10) {
        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"定时计划不超过十条",nil) duration:3];
        return;
    }
    
     CatTimingFeedVController *TimingFeed = [[CatTimingFeedVController alloc]init];
     TimingFeed.bid = self.bid;
     TimingFeed.plan = self.meta_array;
    [self.navigationController pushViewController:TimingFeed animated:YES];
}


- (UITableView*)CatTimingListTableview
{
     if(!_CatTimingListTableview){
         _CatTimingListTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
         _CatTimingListTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
         _CatTimingListTableview.dataSource= self;
         _CatTimingListTableview.delegate = self;
         UIView *view = [[UIView alloc] init];
         view.frame = CGRectMake(0, 0, 0 , 0.01);
         _CatTimingListTableview.tableHeaderView = view;
        [_CatTimingListTableview registerClass:[CatTimingListCell class] forCellReuseIdentifier:@"CatTimingListCell"];
         _CatTimingListTableview.rowHeight = 80;
        [self.view addSubview:_CatTimingListTableview];
        [_CatTimingListTableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.top.equalTo(self.view.mas_top).offset([UIDevice dev_navigationFullHeight]-23);
            make.bottom.equalTo(self.view.mas_bottom);
        }];
    }
    return _CatTimingListTableview;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    CatTimingListModel *model = self.dataArray[indexPath.section];
    CatTimingListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CatTimingListCell" forIndexPath:indexPath];
    cell.list = self.list;
    __weak CatTimingListVController *tempSelf = self;
    __weak CatTimingListCell *tempCell = cell;
    //设置当cell左滑时，关闭其他cell的左滑
    cell.closeOtherCellSwipe = ^{
        for (CatTimingListCell *item in tempSelf.CatTimingListTableview.visibleCells) {
            if (item != tempCell && item.isOpenLeft){
                [item closeLeftSwipe];
            };
        }
    };
    __weak CatTimingListVController *weakSelf = self;
    cell.deleteBlockMember = ^(CatTimingListModel * _Nonnull model) {
        NSLog(@"删除数据");

            FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
        
        /*
            if ([list.is_share intValue]) {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"The invitee does not have permission to change the settings",nil) duration:2];
                
                //设置当cell左滑时，关闭其他cell的左滑
                for (CatTimingListCell *item in tempSelf.CatTimingListTableview.visibleCells) {
                    if (item != tempCell && item.isOpenLeft){
                        [item closeLeftSwipe];
                    };
                }
                return;
            }
        */
        
            if (list.status == 2) {
                [SVProgressHUD showWithDuration:15];
                // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
                __block int timeout = 30*200*5; // 倒计时时间
                weakSelf.cancelpost = NO;
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                weakSelf.wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                dispatch_source_set_timer(weakSelf.wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
                dispatch_source_set_event_handler(weakSelf.wake_up_timer, ^{
                    if(weakSelf.cancelpost){ // 倒计时结束，关闭
                   
                        dispatch_source_cancel(weakSelf.wake_up_timer);
                        weakSelf.wake_up_timer = nil;
                        
                        NSUInteger index =  [self.meta_array indexOfObject:model.feedStr];
                       
                       [self.meta_array removeObjectAtIndex:index];
                       
                       NSArray *valueArray = @[@"control",self.bid,self.meta_array];
                       NSArray *keyArray = @[@"method",@"to",@"meal_plan"];
                       NSDictionary *alternativeDic = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
                       
                       NSError *error;
                       NSData *jsonData = [NSJSONSerialization dataWithJSONObject:alternativeDic options:NSJSONWritingPrettyPrinted error:&error];
                       NSString *pCfgBufString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                       
                       NSLog(@"pCfgBufString-->%@",pCfgBufString);
                       [YKBusinessFramework equesSendData:pCfgBufString];
                        
                    }else{
                        NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                        [YKBusinessFramework equesSendData:Str];
                         timeout-=200;
                        if (timeout <= 0) {
                            dispatch_source_cancel(weakSelf.wake_up_timer);
                            weakSelf.wake_up_timer = nil;
                        }
                    }
                });
                 dispatch_resume(weakSelf.wake_up_timer);
                
            }else if (list.status == 1){
                
                NSLog(@"model.feedStr - >%@",model.feedStr);
             
                if ([self.meta_array containsObject:model.feedStr]) {
                    
                    NSUInteger index =  [self.meta_array indexOfObject:model.feedStr];
                   
                    [SVProgressHUD showWithDuration:30 completionBlock:^{
                        
                    }];
                    
                   [self.meta_array removeObjectAtIndex:index];
                   
                   NSArray *valueArray = @[@"control",self.bid,self.meta_array];
                   NSArray *keyArray = @[@"method",@"to",@"meal_plan"];
                   NSDictionary *alternativeDic = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
                   
                    
                    
                   NSError *error;
                   NSData *jsonData = [NSJSONSerialization dataWithJSONObject:alternativeDic options:NSJSONWritingPrettyPrinted error:&error];
                   NSString *pCfgBufString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                   
                    NSLog(@"pCfgBufString-->%@",pCfgBufString);
                   [YKBusinessFramework equesSendData:pCfgBufString];
                }
          
               
                
            }else{
                if(list.status == 0){
                   [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设备离线无法操作",nil)];
                    return;
                }
            }
    };
    
    cell.timingStatusBlock = ^(BOOL isOn,CatTimingListModel *model) {
        NSLog(@"打开关闭定时 - >%d",isOn);
        
        FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    
        if (list.status == 2){
            [SVProgressHUD showWithDuration:15];
            // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
            __block int timeout = 30*200*5; // 倒计时时间
            weakSelf.cancelpost = NO;
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            weakSelf.wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(weakSelf.wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
            dispatch_source_set_event_handler(weakSelf.wake_up_timer, ^{
                if(weakSelf.cancelpost){ // 倒计时结束，关闭
               
                    dispatch_source_cancel(weakSelf.wake_up_timer);
                    weakSelf.wake_up_timer = nil;
                 
                    NSString *str;
                    if(isOn){
                       str = [model.feedStr stringByReplacingCharactersInRange:NSMakeRange(9,1) withString:@"1"];
                    }else{
                       str = [model.feedStr stringByReplacingCharactersInRange:NSMakeRange(9,1) withString:@"0"];
                    }
                   
                    NSUInteger index =  [self.meta_array indexOfObject:model.feedStr];
                    
                    [self.meta_array replaceObjectAtIndex:index withObject:str];
                    
                    NSArray *valueArray = @[@"control",self.bid,self.meta_array];
                    NSArray *keyArray = @[@"method",@"to",@"meal_plan"];
                    NSDictionary *alternativeDic = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
                    
                    NSError *error;
                    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:alternativeDic options:NSJSONWritingPrettyPrinted error:&error];
                    NSString *pCfgBufString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                    
                     NSLog(@"pCfgBufString-->%@",pCfgBufString);
                    [YKBusinessFramework equesSendData:pCfgBufString];
                    
                    
                }else{
                    NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                    [YKBusinessFramework equesSendData:Str];
                     timeout-=200;
                    if (timeout <= 0) {
                        dispatch_source_cancel(weakSelf.wake_up_timer);
                        weakSelf.wake_up_timer = nil;
                    }
                }
            });
             dispatch_resume(weakSelf.wake_up_timer);
        }else if (list.status == 1){
            
            [SVProgressHUD show];
            NSString *str;
            if(isOn){
               str = [model.feedStr stringByReplacingCharactersInRange:NSMakeRange(9,1) withString:@"1"];
            }else{
               str = [model.feedStr stringByReplacingCharactersInRange:NSMakeRange(9,1) withString:@"0"];
            }
           
            NSUInteger index =  [self.meta_array indexOfObject:model.feedStr];
            
            [self.meta_array replaceObjectAtIndex:index withObject:str];
            
            NSArray *valueArray = @[@"control",self.bid,self.meta_array];
            NSArray *keyArray = @[@"method",@"to",@"meal_plan"];
            NSDictionary *alternativeDic = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
            
            NSError *error;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:alternativeDic options:NSJSONWritingPrettyPrinted error:&error];
            NSString *pCfgBufString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
             NSLog(@"pCfgBufString-->%@",pCfgBufString);
            [YKBusinessFramework equesSendData:pCfgBufString];
            
        }else{
            if(list.status == 0){
               [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设备离线无法操作",nil)];
                return;
            }
        }
    };
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = model;
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  

    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        return 15;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
        return 0.1;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
     UIView *view = [[UIView alloc]init];
     view.backgroundColor = [UIColor whiteColor];
     return view;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
     UIView *view = [[UIView alloc]init];
     view.backgroundColor = [UIColor whiteColor];
    return view;
}



/**
 十六进制转换为二进制
 
 @param hex 十六进制数
 @return 二进制数
 */
- (NSString *)getBinaryByHex:(NSString *)hex {
    
    NSMutableDictionary *hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    [hexDic setObject:@"0000" forKey:@"0"];
    [hexDic setObject:@"0001" forKey:@"1"];
    [hexDic setObject:@"0010" forKey:@"2"];
    [hexDic setObject:@"0011" forKey:@"3"];
    [hexDic setObject:@"0100" forKey:@"4"];
    [hexDic setObject:@"0101" forKey:@"5"];
    [hexDic setObject:@"0110" forKey:@"6"];
    [hexDic setObject:@"0111" forKey:@"7"];
    [hexDic setObject:@"1000" forKey:@"8"];
    [hexDic setObject:@"1001" forKey:@"9"];
    [hexDic setObject:@"1010" forKey:@"A"];
    [hexDic setObject:@"1011" forKey:@"B"];
    [hexDic setObject:@"1100" forKey:@"C"];
    [hexDic setObject:@"1101" forKey:@"D"];
    [hexDic setObject:@"1110" forKey:@"E"];
    [hexDic setObject:@"1111" forKey:@"F"];
    
    NSString *binary = @"";
    for (int i=0; i<[hex length]; i++) {
        
        NSString *key = [hex substringWithRange:NSMakeRange(i, 1)];
        NSString *value = [hexDic objectForKey:key.uppercaseString];
        if (value) {
            
            binary = [binary stringByAppendingString:value];
        }
    }
    return binary;
}



- (unsigned long long)convertHexToDecimal:(NSString *)hexStr {
     unsigned long long decimal = 0;
     NSScanner *scanner = [NSScanner scannerWithString:hexStr];
    [scanner scanHexLongLong:&decimal];
    

    return decimal;
}

/*
 "MON"="一";
 "TUE"="二";
 "WED"="三";
 "THU"="四";
 "FRI"="五";
 "SAT"="六";
 "SUN"="日";
 */
//将7位 0110101 的字符串 通过下标为1表示周几的字符串 拼接成全周期的字符串
- (NSString*)getWeek:(NSString*)weekstr
{
    NSMutableString *str = [[NSMutableString alloc]init];
    for (int i = 0; i < weekstr.length; i ++) {
        
       NSString *indexstr = [weekstr substringWithRange:NSMakeRange(i, 1)];
        if([indexstr isEqualToString:@"1"]){
            switch (i) {
                    case 0:
                    [str appendString:@" 周一"];
                    break;
                   case 1:
                    [str appendString:@" 周二"];
                    break;
                   case 2:
                    [str appendString:@" 周三"];
                    break;
                   case 3:
                    [str appendString:@" 周四"];
                    break;
                   case 4:
                    [str appendString:@" 周五"];
                    break;
                   case 5:
                    [str appendString:@" 周六"];
                    break;
                   case 6:
                    [str appendString:@" 周日"];
                    break;
                   default:
                    break;
               }
        }
    }
    return str;
}



@end
